package com.xuzhao.service;

import com.xuzhao.dao.PersonDao;
import com.xuzhao.entity.Person;

import com.xuzhao.enums.ResultEnum;
import com.xuzhao.exception.PersonException;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * Created by xz on 2017/9/5.
 */
@Service
public class PersonService {

    @Resource
    private PersonDao personDao;

    /**
     * 添加Person
     @Transactional  数据库事务
     * @param person
     * @return
     */
    @Transactional
    public Person saveOrUpdate(Person person){
        return personDao.save(person);
    }

    /**
     * 根据ID查询一个Person
     * @param id
     * @return
     */
    public Person findById(Integer id){
        return personDao.findOne(id);
    }

    /**
     * 查询所有的Person
     * @return
     */
    public List<Person> findAll(){
        return personDao.findAll();
    }

    /**
     * 根据年龄查询
     * @param age
     * @return
     */
    public List<Person> findByAge(Integer age){
        return personDao.findByAge(age);
    }

    /**
     * 删除一个Person
     * @param id
     */
    @Transactional
    public void deleteById(Integer id) throws Exception{
        Person person = findById(id);
        if (person==null){
//            throw new Exception("删除的信息不存在");
            throw new PersonException(ResultEnum.MESSAGE_NOTFOND);
        }else if(person.getAge()>80){
//            throw new Exception("80岁以上允许删除");
            throw new PersonException(ResultEnum.CANNOT_DELETE_BYOUND80);
        }
        personDao.delete(id);
    }
}
